<template>
	<!-- 服务中心信息维护 -->
	<div>
		<!-- 搜索 -->
		<commonSearch @filterChange="changeHandle" @onCollapse="collapseHandle" :defaultStatus="this.getAuditTypes()"/>
		<!-- table -->
		<FilterTable
			ref="table"
			:columns="columns"
			:isSelectColumn="true"
      :defaultSelections="selectionList"
      :onRowSelectChange="rows => this.selectionList = rows"
			:fetchapi="fetchApi"
			:params="fetchParams"
			:datakey="'records'"
			columnsRef='origin_originInfo_maintain_index_01'
			:onColumnsChange="columns => this.columns = columns"
      height="auto"
		>
			<template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-upload" @click="serveExportData()">数据导出</el-button>
				<el-button size="small" type="primary" icon="el-icon-plus" @click="drawerHandle(null,'add')">新增</el-button>
        <el-dropdown trigger="click" @command="handleCommand2" style="margin: 0 10px">
          <el-button type="primary"> 批量下发<i class="el-icon-arrow-down el-icon--right"></i> </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="a">批量下发DMS</el-dropdown-item>
<!--            <el-dropdown-item command="b">批量下发SAP</el-dropdown-item>-->
            <el-dropdown-item command="c" v-show="auths.includes(BATCH_SPC_URL)">批量下发备件中心</el-dropdown-item>
            <el-dropdown-item command="d">批量下发APP</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
<!--        <AjaxButton size="small" type="primary" icon="el-icon-download" :click="issueHandle">下发</AjaxButton>-->
			</template>
		</FilterTable>
		<Drawer
			:visible.sync="visibleDrawer"
			title="服务中心信息"
			destroyOnClose
			:closable=false
			:containerStyle="{width:'70vw', minWidth:'1000px', height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
		>
			<dealerForm v-model="initData"  @close="drawerClose"/>
		</Drawer>
		<Drawer
			:visible.sync="visibleDrawerView"
			title="服务中心信息"
			destroyOnClose
			:containerStyle="{width:'70vw', minWidth:'1000px', height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
		>
			<dealerFormView v-model="initData"  @close="drawerClose"/>
		</Drawer>
		<Drawer
			:visible.sync="visibleDrawerChange"
			title="服务中心信息变更"
			destroyOnClose
			:closable=false
			:containerStyle="{width:'70vw', minWidth:'1000px', height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
		>
			<dealerFormChange v-model="initData" @close="changeDealerInfoClose"/>
		</Drawer>
		<Drawer
			:visible.sync="visibleDrawerChangeList"
			title="服务中心信息信息变更记录"
			destroyOnClose
			:containerStyle="{width:'90vw', minWidth:'1000px', height: '100%', overflow: 'auto'}"
		>
			<dealerFormChangeList v-model="initData" @close="changeDealerInfoListClose"/>
		</Drawer>

	</div>
</template>
<script>
	import commonSearch from './SearchTop';
	import dealerForm from '../serviceDealerForm';
	import dealerFormView from '../serviceDealerForm';
	import dealerFormChange from '../dealerFormChange';
	import dealerFormChangeList from '../dealerFormChange/list';
	import { dictionary } from '@/utils/dictMixin';
	import { region } from '@/api/cms-common/region';//行政区域

	import { findPage,findPage4Serv ,getServeListForExport,sendDealerInfo,sendApp,sendPartSap} from '@/api/cms-api/origin/originInfo';
	import * as types from '@/api/cms-api/origin/originInfo/types';
  import { exportExcelFile } from '@/utils/index';
	import { DICT_CODE } from '@/api/cms-api/origin/commonDealerType';		//服务中心类型工具类
  import { authority } from '@/utils/authMixin';

	export default {
	  name:'serviceDealerBase',
		mixins: [dictionary,region,authority],
		components: {
			commonSearch,dealerForm,dealerFormView,dealerFormChange,dealerFormChangeList
		},
		data() {
			return {
				isSelectColumn: true,
        selectionList:[],
				visibleDrawer: false,
				visibleDrawerView:false,
				visibleDrawerChange:false,
				visibleDrawerChangeList:false,
				columns: this.creatHeader(),
				initData: {},
				fetchApi: findPage4Serv, //ipa 接口
				// fetchParams: {queryByOrgCode:types.QUERY_BY_ORG_VALUE}, //参数
				fetchParams: { shopBusinessTypeStr: 16261002}, //参数
				// fetchParams: {}, //参数
        BATCH_SPC_URL:"/api/cmscloud.channel/dealerAttach/rfc/sendDealer2PartSapBatch",
			};
		},
		mounted() {
			console.log(this.getAuditTypes());
			this.BaseTable = this.$refs.table.$refs.pageTable;
		},
		methods: {

      // 批量下发下拉菜单触发方法
      handleCommand2(command) {
        console.log(command)
        if (command == 'a') {
          this.issueHandle();
        }else if(command == 'd'){
          this.sendApp();
        }else if(command == 'c'){
          this.sendPartSap();
        }
      },
			//获取状态（需要显示的）
			getAuditTypes(){
				return [types.DEALER_INFO_STATUS_SAVED,types.DEALER_INFO_STATUS_CONSTRUCTION_ACCEPTANCE_CHANGE_INTO];
			},
      getBusinessTypes() {
			  return [types.SHOP_BUSINESS_SERVICE, types.SHOP_BUSINESS_SALES_AND_SERVICE];
      },
			//搜索获取数据
			changeHandle(val) {
        // val.serviceShopType = val.serviceShopType.toString();
				this.fetchParams = Object.assign({shopBusinessTypeStr: 16261002},val);
			},
			drawerHandle(row, type) {
				let id = -1;
				let lastTimeSendToDms = null;
				if(type != 'add'){
					id = row.dealerAttachId
          lastTimeSendToDms = row.lastTimeSendToDms
				}
				this.initData = {
					type: type, //add/edit/show
					examineType:'show',//设置主表单内容为只读
					isExamine:false,//打开审核按钮和输入框
					formType:types.DEALER_INFO_FORM_STATUS_MAINTAIN_OEM,
					id: id,  //表主键
          lastTimeSendToDms: lastTimeSendToDms
				};
				if(type == 'show'){
					this.visibleDrawerView = true;
				}else{
					this.visibleDrawer = true;
				}
			},
			drawerClose(type) {
				this.visibleDrawer = false;
				this.visibleDrawerView = false;
				if (type === 'refresh') {
					// 重新加载
					this.fetchParams = { ...this.fetchParams };
				}
			},
      // 服务中心基础信息维护导出
      async serveExportData() {
        await getServeListForExport(this.fetchParams).then(res => {
          console.log(res);
          exportExcelFile(res.data, '服务中心基础信息维护导出');
        });
      },
			/**
			 * 变更服务中心信息
			 */
			changeDealerInfo(row) {
				let id = row.dealerAttachId;
				this.initData = {
					type: 'edit',
					examineType:'show',//设置主表单内容为只读
					isExamine:false,//打开审核按钮和输入框
					formType:types.DEALER_INFO_FORM_STATUS_SUBMISSION_DLR,
					id: id,  //表主键
          lastTimeSendToDms: row.lastTimeSendToDms
				};
				this.visibleDrawerChange = true;
			},
			/**
			 * 变更服务中心信息关闭
			 */
			changeDealerInfoClose(data) {
				this.visibleDrawerChange = false;
				if (data.type === 'refresh') {
					// 重新加载
					this.fetchParams = { ...this.fetchParams };
				}
				console.log(data);
			},
			/**
			 * 变更服务中心历史
			 */
			changeDealerInfoHistory(row) {
				console.log(row);
				let dealerAttachId = row.dealerAttachId;
				this.initData = {
					dealerAttachId: dealerAttachId  //表主键
				};
				this.visibleDrawerChangeList = true;
			},
			changeDealerInfoListClose(data) {
				this.visibleDrawerChangeList = false;
				if (data.type === 'refresh') {
					// 重新加载
					this.fetchParams = { ...this.fetchParams };
				}
			},
			collapseHandle() {
				this.$nextTick(() => {
					this.BaseTable.EXECUTE_RESET_HEIGHT();
				});
			},
      //下发
      async issueHandle(){
        let rows = this.selectionList;
        if(rows.length == 0){
          this.$message.warning("至少选择一条记录");
          return;
        }
        let ids = new Array();
        rows.forEach(row => {
          ids.push(row.dealerCompanyId);
        });
        const res = await sendDealerInfo(ids.join(","));
        if(res.resultCode == 200){
          this.$notify.success("下发成功");
        }

        // 刷新列表数据
        this.fetchParams = { ...this.fetchParams };
      },
      //下发app
      async sendApp() {
        let rows = this.selectionList;
        if (rows.length == 0) {
          this.$message.warning('至少选择一条记录');
          return;
        }
        let ids = new Array();
        rows.forEach((row) => {
          ids.push(row.dealerAttachId);
        });
        const res = await sendApp(ids.join(','));
        if (res.resultCode == 200) {
          this.$notify.success('下发成功');
        }

        // 刷新列表数据
        this.fetchParams = { ...this.fetchParams };
      },
      //下发备件中心
      async sendPartSap() {
        let rows = this.selectionList;
        if (rows.length == 0) {
          this.$message.warning('至少选择一条记录');
          return;
        }
        let ids = new Array();
        rows.forEach((row) => {
          ids.push(row.dealerAttachId);
        });
        const res = await sendPartSap(ids.join(','));
        if (res.resultCode == 200) {
          this.$notify.success('下发成功');
        }

        // 刷新列表数据
        this.fetchParams = { ...this.fetchParams };
      },
			//table表头和数据源
			creatHeader() {
				return [
					{ title: '序号', dataIndex: 'index', width: 80, sorter: true,
						render: props => {
							return <span>{props.row.index + 1}</span>;
						}
					},
					{ title: '操作', dataIndex: 'column-action', fixed: 'left',
						render: (props, h) => {
							let editBtn,editBtnEnd,changeBtn,changeBtnEnd,changeListBtn,changeListBtnEnd;
							if(true){
								editBtn = (
									<el-button size="mini" type="text" onClick={() => this.drawerHandle(props.row,'edit')}>
									编辑
									</el-button>
								);
								editBtnEnd = (<el-divider direction="vertical" />);
							}
							// //如果审核通过了，则可以变更
							// if(props.row.auditStatus === types.DEALER_INFO_STATUS_AUDITED){
							// 	changeBtnEnd = (<el-divider direction="vertical" />);
							// 	changeListBtnEnd = changeBtnEnd;
							// 	changeBtn = (
							// 		<el-button size="mini" type="text" onClick={() => this.changeDealerInfo(props.row)}>
							// 			变更
							// 		</el-button>
							// 	);
							// 	changeListBtn = (
							// 		<el-button size="mini" type="text" onClick={() => this.changeDealerInfoHistory(props.row,'show')}>
							// 			变更历史
							// 		</el-button>
							// 	);
							// }
							return (
								<div>
									{editBtn}
									{editBtnEnd}
									<el-button size="mini" type="text" onClick={() => this.drawerHandle(props.row,'show')}>
									查看
									</el-button>
									{changeBtnEnd}
									{changeBtn}
									{changeListBtnEnd}
									{changeListBtn}
								</div>
							);
						}
					},
          { title: '公司代码', dataIndex: 'dealerCompanyCode', sorter: true ,filter:true ,filterType:'input'},
          { title: '服务中心代码', dataIndex: 'dealerCode', sorter: true ,filter:true ,filterType:'input'},
          { title: '服务中心名称', dataIndex: 'dealerName', sorter: true ,filter:true ,filterType:'input'},
          { title: '服务中心简称', dataIndex: 'dealerShortname', sorter: true ,filter:true ,filterType:'input'},
          { title: '服务战区', dataIndex: 'serviceWarAreaName', sorter: true ,filter:true ,filterType:'input'},
          { title: '服务大区', dataIndex: 'serviceBigAreaName', sorter: true ,filter:true ,filterType:'input'},
          // { title: '大区经理', dataIndex: 'serviceBigAreaManager', sorter: true ,filter:true ,filterType:'input'},
          { title: '服务小区', dataIndex: 'serviceSmallAreaName', sorter: true ,filter:true ,filterType:'input'},
          // { title: '小区经理', dataIndex: 'serviceSmallAreaManager', sorter: true ,filter:true ,filterType:'input'},
          { title: '省份', dataIndex: 'provinceName', sorter: true ,filter:true ,filterType:'input'},
          { title: '城市', dataIndex: 'cityName', sorter: true,filter:true ,filterType:'input'},
          { title: '县区', dataIndex: 'districtName', sorter: true,filter:true ,filterType:'input'},
					{ title: '经营状态', dataIndex: 'dealerStatus', sorter: true,
						render: props => {
							return <span>{this.createDictText(props.row.dealerStatus, '1724')}</span>;
						}
            ,filter:true
            ,filterType:'checkbox'
            ,filterItems:this.createDictList('1724')
					},
          // { title: '网点类型', dataIndex: 'branchType', sorter: true,
          //   render: props => {
          //     return <span>{this.createDictText(props.row.branchType, '1623')}</span>;
          //   }
          //   ,filter:true
          //   ,filterType:'checkbox'
          //   ,filterItems:this.createDictList('1623')
          // },
				];
			},
		},
	};
</script>

<style lang="less" scoped>
</style>
